package observer;

import java.awt.*;
import java.io.Serializable;
import java.util.ArrayList;

/**
 * These ints can be observed by {@link ColourObserver}s, i.e. the observers will be notified of any changes.
 *
 * @author Neil Dickson
 */
public final class ObservedColour implements Copiable<ObservedColour>, Serializable {
	private int							argb;
	private Color						colour;
	private ArrayList<ColourObserver>	observers;

	public ObservedColour(int argb) {
		this.argb = argb;
		colour = new Color(argb,true);
		observers = null;
	}

	public synchronized void addObserver(ColourObserver observer) {
		if (observer==null) {
			throw new NullPointerException();
		}
		if (observers==null) {
			observers = new ArrayList<ColourObserver>();
		}
		observers.add(observer);
	}
	public synchronized void removeObserver(ColourObserver observer) {
		if (observers!=null && observers.contains(observer)) {
			observers.remove(observer);
		}
	}

	public int get() {
		return argb;
	}
	public Color getColour() {
		return colour;
	}
	public void set(int i) {
		set(null,i);
	}
	public void set(ColourObserver culprit,int argb) {
		// Avoid creating a new object if the previous value is the same
		if (this.argb!=argb) {
			this.argb = argb;
			colour = new Color(argb,true);
			updateAllBut(culprit);
		}
	}

	public String toString() {
		String s = Integer.toString(argb,16);
		while (s.length()<8) {
			s+="0";
		}
		return s;
	}

	public ObservedColour copy() {
		return new ObservedColour(argb);
	}

	private void updateAllBut(ColourObserver culprit) {
		if (observers!=null) {
			for (ColourObserver observer : observers) {
				if (observer!=culprit) {
					observer.valueChanged(this);
				}
			}
		}
	}
}